package com.elitel.frame.base.component.quartz;

import com.alibaba.fastjson.JSON;
//import com.elitel.common.redis.service.RedisCacheService;
import com.elitel.frame.base.component.RedisCacheComponent;
import com.elitel.frame.base.component.RedisKey;
import com.elitel.frame.base.service.BaseQueryfieldcacheService;
import com.elitel.frame.base.service.SysFunctionService;
import com.elitel.frame.business.controller.SingleTableServerController;
import com.elitel.frame.business.service.SingleTableServerService;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.CfgExtend;
import com.elitel.frame.main.entity.SysFunction;
import com.elitel.frame.main.entity.enums.DateTimeFormat;
import com.elitel.frame.main.entity.ext.BaseQueryfieldcacheExt;
import com.elitel.frame.main.entity.vo.PageResponseVo;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class QueryFieldCacheQuartz implements Job {

    private static final Logger logger = LoggerFactory.getLogger(QueryFieldCacheQuartz.class);

    @Autowired
    private BaseQueryfieldcacheService baseQueryfieldcacheService;
    @Autowired
    private RedisCacheComponent redisCacheComponent;
    @Autowired
    private RedisKey redisKey;
    @Value("${cache.dataredis.library:#{2}}")
    private int redisindex;//RedisDbIndex.value;
    @Value("${spring.jackson.date-format}")
    private String dateformat;
    @Autowired
    private SingleTableServerController singleTableServerController;
    @Autowired
    private SysFunctionService sysFunctionService;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

            JobDetail jobDetail = context.getJobDetail();

        String jobId = jobDetail.getJobDataMap().getString("serviceId");
        String[] configArray = jobId.split("\\|");
        if (configArray.length < 3)
            return;

        String serviceId = configArray[0].trim();
        String serviceType = configArray[1].trim();
        String parmeterGroup = configArray[2].trim();

        logger.info("QueryFieldCacheQuartz任务执行开始执行，服务："+serviceId);

        PageResponseVo pageResponse = new PageResponseVo();
        CfgExtend cfgExtend = redisCacheComponent.cfgExtendRedisCache(serviceId);
        if(cfgExtend.getSyscatch() <= 0)
            return;
        CfgDb prop = redisCacheComponent.cfgDBRedisCache(cfgExtend.getDbKey());
        //获取缓存条件集合
        List<BaseQueryfieldcacheExt> parmeterlist = baseQueryfieldcacheService.queryCacheFieldByServiceIdGroupId(serviceId, serviceType, parmeterGroup);
        if(parmeterlist == null && parmeterlist.size() <= 0)
            return;
        Map<String,String> conQueryMap = new HashMap<>();
        String conQuery = "";
        //条件拼接；
        conQuery += "{";
        for (BaseQueryfieldcacheExt bqfe : parmeterlist) {
            //自定义格式处理
            if(null == bqfe.getParameterconfig() || "customDefind".equals(bqfe.getParameterconfig()) || "".equals(bqfe.getParameterconfig())) {
                conQuery += "\"" + bqfe.getParametercode() + "\":" + "\"" + (StringUtils.isBlank(bqfe.getParametervalue()) ? "" : bqfe.getParametervalue()) + "\",";
                conQueryMap.put(bqfe.getParametercode(), (StringUtils.isBlank(bqfe.getParametervalue()) ? "" : bqfe.getParametervalue()));
            } else {
                //根据函数获取数据
                SysFunction func = sysFunctionService.getSysFunctionByGuid(bqfe.getParameterconfig());
                if(null == func.getFuncscript() || "".equals(func.getFuncscript()))
                    return;
                String paramvalue = bqfe.getParametervalue() == null ? "" : bqfe.getParametervalue();
                String funcname = StringUtils.substringBefore(paramvalue, "(").trim();
                String parmeters = StringUtils.substringBetween(paramvalue,"(",")").trim();
                String scriptValue = execFunctionScript(func.getFuncscript(),funcname,parmeters );
                conQuery += "\"" + bqfe.getParametercode() + "\":" + "\"" + scriptValue + "\",";
                conQueryMap.put(bqfe.getParametercode(), scriptValue);

            }
        }
        conQuery += "}";
        String rediskey_K = "";
        //Object datalist = singleTableServerController.querySingleTable(serviceId, null, null, conQuery, "true");
        //分页只取500条
//        if(null != cfgExtend.getIspagination() && cfgExtend.getIspagination() == 1){
//            rediskey_K = redisKey.generate(serviceId,conQueryMap,serviceType,"1", "1");
//            pageResponse = singleTableServerService.queryDataByPage(prop, cfgExtend, "1", "500", conQuery);
//        } else if (null != cfgExtend.getIspagination() && cfgExtend.getIspagination() == 0){
//            rediskey_K = redisKey.generate(serviceId,conQueryMap,serviceType,"1", "");
//            pageResponse = singleTableServerService.querySingleTBList(prop, cfgExtend, conQuery);
//        }
//
//        if(null == pageResponse.getRows() || pageResponse.getRows().size() <= 0)
//            return;
//
//        String extendStr = JSON.toJSONStringWithDateFormat(pageResponse.getRows(),"yyyy-MM-dd HH:mm:ss");
//        redisCacheService.saveObjectTimeOut(rediskey_K, extendStr, redisindex, (cfgExtend.getCatchtime() * 60));
        logger.info("QueryFieldCacheQuartz任务执行缓存热数据成功！服务："+serviceId);


    }


    /**
     * 执行js函数function获取返回值
     * @param script(js脚本)
     * @param funcname(方法名)
     * @param parmeter(以逗号分隔的参数)
     * @return
     */
    private String execFunctionScript(String script, String funcname, String parmeter) {
        String res = "";
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine se = sem.getEngineByName("javascript");
        try {
            String[] parmeters = parmeter.split(",");
            se.eval(script);
            Invocable inv2 = (Invocable) se;
            res = (String) inv2.invokeFunction(funcname, parmeters);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

//     public static void main(String[] args) {
//         String reg = "^\\w+\\([\\s\\S]*\\)";
//         Pattern p = Pattern.compile(reg);
//         Matcher m = p.matcher("say (123, 123)".replace(" ",""));
//         System.out.println(m.matches());
// //        ScriptEngineManager sem = new ScriptEngineManager();
// //        ScriptEngine se = sem.getEngineByName("js");
// //        try {
// //            String[] parmeters = {"3", "yyyy-MM-dd"};
// //            String script = "function threedaysago(day, format) {\n" +
// //                    "\tvar curDate = new Date();\n" +
// //                    "\tvar stringDate = new Date(curDate.getTime() - day*24*60*60*1000).format(format);\n" +
// //                    "}";
// //            se.eval(script);
// //            Invocable inv2 = (Invocable) se;
// //            String res = (String) inv2.invokeFunction("threedaysago", parmeters);
// //
// //            System.out.println(res);
// //        } catch (Exception e) {
// //            e.printStackTrace();
// //        }
//     }
}
